package com.acme.bankapp.service.bank;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.acme.bankapp.domain.bank.Email;
import com.acme.bankapp.domain.bank.Queue;
import com.acme.bankapp.domain.bank.QueueImpl;

public class EmailService {
	private static Lock lock = new ReentrantLock();	
	private static volatile EmailService instance;
	private Queue queue = new QueueImpl();
	private boolean closed;
	public EmailService() {
		new Thread( new Runnable() {
			@Override
			public void run() {
				while(!Thread.interrupted()) {
					sendNotificationEmail();
				}
			}
		}).start();
	}
	
	public static EmailService getEmailService() {
		lock.lock();
		if(instance == null) {
			instance = new EmailService();
		}
		if(instance != null) {
			return instance;
		} else return null;
	}
	
	public void addEmail(Email email) {
		if(!closed) {
			queue.addEmail(email);
		}
	}
	
	public void sendNotificationEmail() {
		if(!closed) {
			System.out.println(queue.getEmail().toString());	
		} else {
			if(!queue.isEmpty()) {
				System.out.println(queue.getEmail().toString());
			} else {
				Thread.currentThread().interrupt();
			}
		}
	}

	public void close() {
		closed = true;
	}
	
	public Queue getQueue() {
		return queue;
	}
}
